<?php
/*
This file is part of TorrentParse 2.1.

    TorrentParse is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    TorrentParse is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with TorrentParse; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    TorrentParse. TorrentParse parses bittorrent torrent files in PHP for use in web sites.
    Copyright (C) 2004 TorrentNews.tk

System Requirements:
PHP 4.*.* with sha1 function
Written on PHP 4.3.4
Untested on any other version

This code is not designed to give the smallest filesize, operate as fast as possible.
It is designed so as little can go wrong as possible, which to me is the most important thing.
This can be cleaned up a lot and made faster too
Based on BEncode, BDecode from PHPBTTRACKER.
Uses code snippets from DUMPTORRENTCGI.PHP.
PHPBTTRACKER is licenced under the GPL
Each term has been assigned a variable so that it can be used for further processing

CHANGES
Many more torrent variables added (mostly TorrentAid hashes)
"File cannot be found error", "File cannot be opened" and "File not Valid" errors added
function checkarray() added to reduce the amount of if((isset))s.
Name changed to "Internal File name" to reduce confusion

*/

// Please Change $seedsandpeers to TRUE or FALSE if you want seeds and peers to be checked

$seedsandpeers = TRUE;

// End of config area
error_reporting  (0);

function pathurlencode($uri) {
        $uri = urlencode($uri);
        $uri = str_replace('%3A', ':', $uri);
        $uri = str_replace('%2F', '/', $uri);
        $uri = str_replace('%26', '&', $uri);
        $uri = str_replace('%40', '@', $uri);
        $uri = str_replace('%3A', ':', $uri);
        $uri = str_replace('%3F', '?', $uri);
        $uri = str_replace('%3D', '=', $uri);
        $uri = str_replace('%5B', '[', $uri);
        $uri = str_replace('%5D', ']', $uri);
        return $uri;
    }
    // From php.net
    function getfilesize($bytes) {
   if ($bytes >= 1099511627776) {
       $return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
       $suffix = "TB";
   } elseif ($bytes >= 1073741824) {
       $return = round($bytes / 1024 / 1024 / 1024, 2);
       $suffix = "GB";
   } elseif ($bytes >= 1048576) {
       $return = round($bytes / 1024 / 1024, 2);
       $suffix = "MB";
   } elseif ($bytes >= 1024) {
       $return = round($bytes / 1024, 2);
       $suffix = "KB";
   } else {
       $return = $bytes;
       $suffix = "Byte";
   }
   if ($return == 1) {
       $return .= " " . $suffix;
   } else {
       $return .= " " . $suffix . "s";
   }
   return $return;
}

 function Parse($filename) {
        require_once("BDecode.php") ;
        require_once("BEncode.php") ;
            global $seedsandpeers;
       $torrent = explode(".", $filename);
    $fileend = end($torrent);
    $fileend = strtolower($fileend);
if ( $fileend == "torrent" ) {
// It is important that ./torrents/ exists or else someone can pass a string to read /etc/passwd like people have been doing on the homepage
$stream = @file_get_contents("./torrents/$filename");
if ($stream == FALSE) {
echo "$filename cannot be opened" ;

}
if(!isset($stream)){
echo "Error in Opening file." ;
    }else{
            $array = BDecode($stream);
if ($array === FALSE){
echo "Error in file. Not valid BEncoded Data." ;

}else{
if(array_key_exists("info", $array) === FALSE){
echo "Error in file. Not a valid torrent file." ;

}else{

// Displays File Name
echo "Torrent Filename: "        ;
echo $filename ;
// Torrent Tracker
              echo "<br>Torrent Announce URL: ";
        $announce = $array["announce"];
        echo $announce;

                             if (isset($array["announce-list"])){
                echo "<br>This Torrent also has several backup trackers";

              // Loops through the list of Backup Trackers
                foreach ($array["announce-list"] as $alist)
                {
                echo "<br>Tracker: ";
                 echo $alist[0];
                          }
                }

        // Stores 2D array as variable. The whole of $array['info'] is now called as $infovariable
        $infovariable = $array["info"];
             // Calculates SHA1 Hash
                      echo "<br>Torrent Info Hash: ";
      $infohash = sha1(BEncode($infovariable));
       echo $infohash ;
            //Calculates EDonkey2000 hash (ED2K) if present
      if (isset($infovariable["ed2k"])){
              $ed2k = $infovariable["ed2k"];
              $hexed2k = bin2hex($ed2k);
               echo "<br>Edonkey2000 Hash: ";
              echo $hexed2k;                            }
            // Prints MD5SUM if present
     if (isset($infovariable['md5sum'])){
                echo "<br>MD5SUM: ";
                echo $infovariable['md5sum'];
                }
        if (isset($infovariable['sha1'])){
                echo "<br>SHA1 Hash (TorrentAid): ";
                $hexsha1 = bin2hex($infovariable["sha1"]);
                echo $hexsha1 ;
                }
      // Calculates date from UNIX Epoch
      echo "<br>Torrent Creation Date: ";
    $makedate = date('r' , $array["creation date"]);
echo $makedate ;
   // The name of the torrent is different to the file name
   echo "<br>Internal Filename of Torrent: " ;
    echo $infovariable['name'] ;

if (isset($infovariable["files"]))  {
echo "<br>This is a Multifile Torrent" ;
$filecount = "";
      foreach ($infovariable["files"] as $file)
                        {
                         $filecount += "1";
                        // Loops through multifile torrent names
                                 echo "<br>";
                                 echo $filecount;
                                 echo ": File Name: ";
                         $multiname = $file['path'];
                         echo $multiname[0];
                         echo ". File Size: " ;
   $multitorrentsize = $file['length'];
   echo getfilesize($multitorrentsize) ;
   $torrentsize += $file['length'];
       if (isset($file["ed2k"])) {
     echo "<br>Edonkey2000 Hash: ";
             $multied2k = bin2hex($file["ed2k"]);
             echo $multied2k ;
                         }
             if (isset($file["sha1"])) {
             echo "<br>SHA1 Hash: ";
             $multisha1 = bin2hex($file["sha1"]);
            echo $multisha1 ;

                        }
                         if (isset($file["MD5SUM"])) {
             echo "<br>MD5SUM: ";
             $multimd5 = bin2hex($file["MD5SUM"]);
           echo $multimd5;


                        }

                        } echo "<BR>Combined File Size: ";
                                echo getfilesize($torrentsize);

        }
        else {
        // Calculates File size in KB and rounds to 2 decimal places
       echo "<br>File Size: ";
       $torrentsize = $infovariable['length'];
       echo getfilesize($torrentsize);
        }
   // Calculates Piece Size in KB
   echo "<br>Piece Size: " ;
   echo getfilesize($infovariable['piece length']);


   // For terms that are only included in certain torrent files (Mostly TorrentAid)
if(isset($array['comment'])) {
echo "<br>Torrent Comment: " ;
echo $array['comment'];
}
if(isset($array['created by'])) {
echo "<br>Torrent Created By: " ;
echo $array['created by'] ;
}
if(isset($array['encoding'])) {
echo "<br>Torrent Encoding: " ;
echo $array['encoding'] ;
}
if(isset($array['user-agent'])) {
echo "<br>Torrent File Creator: " ;
echo $array['user-agent'];
}
if(isset($array['httpseeds'])) {
foreach ($array["httpseeds"] as $httpseed)
                        {
                                  echo "<br>Webseed URL: " ;
                                 echo $httpseed;
}
}
// global $seedsandpeers;
if ($seedsandpeers === TRUE){
if (isset($array["announce"])){
$announce = $array["announce"];
// Possibly HtTp://
$announce = strtolower($announce);
if (substr($announce, 0, 7) === "http://"){
if ((substr_count($announce, "/announce")) == 1){
$scrape = str_replace('/announce', '/scrape', $announce);
$httpget = "?info_hash=";
$binsha1 = pack("H*", $infohash);
$binsha1s = addslashes($binsha1);
$fullurl = "$scrape$httpget$binsha1";
$httpurl = pathurlencode($fullurl);
sapeerconnect($httpurl, $binsha1s, $torrentsize);
}  else {
$error = "<BR>Bad Tracker URL for scraping (Maybe trackerless torrent)." ;
echo $error;
}
}
else {
$error = "<BR>Bad Tracker URL for scraping (Maybe trackerless torrent)." ;
echo $error;
}
}
}
        }
}
}
}


}

function sapeerconnect($httpurl, $binsha1s, $torrentsize) {
   // Code from yabtuc-0.4.1
$fp = fopen($httpurl, "rb");
$stream = "";
        if ($fp) {
            while( !feof( $fp ) ) {
                $stream .= @fread($fp, 128);
}
}
fclose($fp);


if($fp === FALSE){
$error = "<BR>No Response From Tracker. Please Try Again." ;
echo $error;
}
else{

$decoded = BDecode($stream);
if ($decoded["files"] === TRUE) {
$error = "<BR>File not present on tracker (torrent may be dead).";
echo $error;
}
else
{
$files = $decoded["files"];
$sha1tor = $files[$binsha1s];
if(isset($files[$binsha1s])) {


echo "<BR>Seeds:";
echo $sha1tor['complete'];
echo "<BR>Peers:";
echo $sha1tor['incomplete']  ;
// FBT2 shows no completed downloads and others
if(isset($sha1tor['downloaded'])){
echo "<BR>Completed Downloads:";
echo $sha1tor['downloaded'];
if(isset($torrentsize)){
// Something to try and calculate some bandwidth figures
$bandwidth = $sha1tor['downloaded'] * $torrentsize ;
echo "<BR>Estimated Total Bandwidth used in downloading: ";
echo getfilesize($bandwidth);
}

}
}
else
{
$error = "<BR>Error with tracker response." ;
echo $error ;
}
}



}


}

// Checks to see that a torrent name is in GET
if (isset($_GET['filename']))  {
              Parse($_GET['filename']);
      }
                else {
                           echo "No torrent name has been specified. Please Specify One.";
                }

?>